<template>
  <van-image width="100%" height="350" :src="product.thumbs_text" />

  <div class="detailbox">
    <h4>{{ product.name }}</h4>
    <div class="price">
      单独购买：<em>￥</em>{{ product.price }} |
      拼团价格：<em>￥</em>{{ product.team }}
    </div>
  </div>

  <div class="allkbox"></div>

  <!-- 商品规格 -->
  <div class="info_choice">
    <!-- Sku 商品规格 -->
    <div class="commodity" @click="SkuShow = true">
      <div class="opt">
        <div class="title wanl-gray">选择</div>
        <div class="option">
          <div class="selected">
            <div>
              <span>尺码</span>
              <span>颜色</span>
            </div>
          </div>
        </div>
      </div>
      <div class="wanl-gray">
        <img src="/assets/images/go.png" />
      </div>
    </div>
    <!-- 服务 -->
    <div class="commodity" @click="TipShow = true">
      <div class="opt">
        <div class="title wanl-gray">服务</div>
        <div class="option">
          <div class="selected">
            <div>
              <span>7天无理由退款</span>
              <span>·</span>
              <span>24小时内发货</span>
              <span>·</span>
              <span>极速退款</span>
            </div>
          </div>
        </div>
      </div>
      <div class="wanl-gray">
        <img src="/assets/images/go.png" />
      </div>
    </div>
  </div>

  <div class="allkbox"></div>

  <!-- 选项卡 -->
  <van-tabs v-model:active="TabActive" type="card" color="#EE0A24">
    <van-tab title="产品参数">
      <div v-html="product.content"></div>
    </van-tab>
    <van-tab title="商品评价">
      <!-- 下拉刷新 -->
      <van-pull-refresh v-model="refreshing" @refresh="refresh">
          <!-- 加载列表 -->
          <van-list
            v-model:loading="loading"
            :finished="finished"
            :offset="10"
            :immediate-check="true"
            finished-text="暂无更多数据"   
            @load="load"
          >
            <div class="rate" style="overflow-x: hidden;">
              <div class="rate-header">
                <div class="rate-score">
                  <h4>与描述相符</h4>
                  <strong>4.5</strong>
                </div>
                <div class="rate-graph">
                  <van-rate v-model="rate" allow-half readonly />
                </div>
              </div>

              
                <div class="rate-content">
                  <div v-if="list">
                    <div class="review-box" v-for="(item,key) in list" :key="key">
                      <div class="review-item">
                        <!-- 评论人 -->
                        <div class="from-whom">
                          <div class="avatar">
                            <img :src="item.business.avatar_text" alt="" />
                          </div>
                          <div class="name">{{item.business.nickname ? item.business.nickname : '暂无昵称'}}</div>
                        </div>

                        <!-- 评论内容 -->
                        <div class="review-details">
                          <div class="content">{{item.comment}}</div>
                          <div>
                              <img :src="item.thumbs_text" alt="">
                          </div>
                          <div class="time">{{item.comtime_text}}</div>
                          <van-rate v-model="item.rate" allow-half readonly />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
            </div>
        </van-list>
      </van-pull-refresh>
    </van-tab>
  </van-tabs>

  <!-- SKU -->
  <van-sku ref="SkuRef" v-model="SkuShow" :sku="sku" :properties="properties" :goods="goods" :goods-id="product.id"
    @buy-clicked="Buy" @add-cart="AddCart">
    <!-- 自定义 sku actions -->
    <template #sku-actions="props">
      <div class="van-sku-actions">
        <van-button square size="large" type="warning" @click="props.skuEventBus.emit('sku:addCart')">加入购物车</van-button>

        <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
        <van-button square size="large" type="danger" @click="props.skuEventBus.emit('sku:buy')">单独购买</van-button>

        <van-button square size="large" type="danger" @click="JoinTeam">参与拼团</van-button>
      </div>
    </template>
  </van-sku>

  <!-- 服务保障 -->
  <van-action-sheet v-model:show="TipShow" title="服务保障">
    <div class="ProductTip">
      <h4>7天无理由退货</h4>
      满足相应条件下，卖家需支持7天无理由，其中定制订单不支持“7天无理由退货”。
      <h4>晚发必赔</h4>
      若商家未按订单约定的时间发货，您可以在订单详情申请赔付
      <h4>极速退款</h4>
      在符合一定的退款申请原因、时效和退款金额范围内，可享受0秒退款服务。
    </div>
  </van-action-sheet>

  <!-- 底部导航栏 -->
  <van-action-bar>
    <van-action-bar-icon icon="chat-o" text="客服" />
    <van-action-bar-icon icon="cart-o" @click="ToCart" text="购物车" :badge="product.cart" v-if="product.cart"/>
    <van-action-bar-icon icon="cart-o" @click="ToCart" text="购物车" v-else />
    <van-action-bar-icon icon="star" text="已收藏" color="#ff5000" @click="collection" v-if="product.collection" />
    <van-action-bar-icon icon="star-o" text="收藏" @click="collection" v-else />
    <van-action-bar-button type="danger" text="立即购买" @click="SkuShow = true" />
  </van-action-bar>

</template>

<script setup>
import VanSku from 'vant-sku';
import 'vant-sku/dist/index.css'
const { proxy } = getCurrentInstance();

//商品id
let proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0
let product = ref({})

//拼团id
let teamid = proxy.$cookies.get('teamid') ? proxy.$cookies.get('teamid') : 0;

//选项卡
let TabActive = ref(0)
let rate = ref(4.5)

//Sku
let SkuShow = ref(false)
let sku = ref({})
let properties = ref([])
let goods = ref({})
let SkuRef = ref({})

//服务保障
let TipShow = ref(false)

//下拉刷新的数据
let list = ref([]) //数据列表
let page = ref(1) //分页
let loading = ref(false) //加载状态
let finished = ref(false) //是否无更多数据
let refreshing = ref(false) //下拉刷新

//生命周期
onBeforeMount(() => {
  info()
})

//获取商品详细
const info = async () => {
  var params = { proid }

  //判断是否有没有登录
  if (proxy.$business.value.id) {
    params.busid = proxy.$business.value.id
  }

  var result = await proxy.$POST({
    url: '/product/info',
    params: params
  })

  if (result.code == 0) {
    proxy.$fail({
      message: result.msg,
      duration: 1000,
      onClose: () => proxy.$router.go(-1)
    })
    return false
  }

  let ProductData = result.data.product
  let SkuData = result.data.sku
  let PropertiesData = result.data.properties

  product.value = ProductData

  // sku
  goods.value = { picture: ProductData.thumbs_text }
  sku.value = SkuData
  properties.value = Object.values(PropertiesData)
}

//下拉刷新
const refresh = async () =>
{
    //清空查询参数
    page.value = 1
    list.value = []
    finished.value = false
    loading.value = true
    //加载数据方法
    load()
}

//加载数据方法 查询订单数据
const load = async () =>
{
    //判断是否为加载中的状态
    if(refreshing.value)
    {
        refreshing.value = false
    }

    //组装数据
    var params = {
        page: page.value,
        proid
    }

    //发起请求
    var result = await proxy.$POST({
        url: '/product/comment',
        params
    })

    //请求发送完毕后，加载状态也就完毕了
    loading.value = false
    
    //如果没有更多数据了 就说明已经加载到底了
    if(result.code == 0)
    {
        finished.value = true
        return;
    }

    let CommentData = result.data.comment

    //星级评分 需要给数值类型
    CommentData.map(item => item.rate = parseFloat(item.rate))

    list.value = list.value.concat(CommentData)
    page.value++

}


//添加收藏
const collection = async () => {
  if (!proxy.$business.value.id) {
    proxy.$fail('请先登录')
    return false
  }

  //请求
  var result = await proxy.$POST({
    url: '/product/collection',
    params: {
      busid: proxy.$business.value.id,
      collectid: proid,
    }
  })

  if (result.code == 0) {
    proxy.$fail(result.msg)
    return false
  }

  product.value.collection = result.data == 'add' ? true : false
}

//添加购物车
const AddCart = async (SkuData) =>
{
  //判断是否登录
  if(!proxy.$business.value.id)
  {
    proxy.$fail('请先登录')
    return false
  }

  //判断是否选择商品规格
  if(properties.value.length > 0 && !SkuData.selectedSkuComb)
  {
    proxy.$fail('请选择商品规格')
    return false
  }

  //购买数量
  var selectedNum = SkuData.selectedNum
  if(selectedNum <= 0)
  {
    proxy.$fail('购买数量不能小于等于0')
    return false
  }

  var relationids = []

  //有规格
  if(properties.value.length > 0)
  {
    var SkuProps = SkuData.selectedSkuComb.properties
    
    for(var item of SkuProps)
    {
      var id = item.v[0] ? item.v[0]['id'] : 0;
      if(id) relationids.push(id)
    }
  }
  //组装数据
  var params = {
    busid: proxy.$business.value.id,
    proid: proid,
    nums: selectedNum,
    relationids: relationids.join(','),//规格id
  }

  var result = await proxy.$POST({
    url: '/cart/add',
    params
  })

  //隐藏弹出框
  SkuShow.value = false

  if(result.code == 0)
  {
    proxy.$fail(result.msg)
    return false
  }

  proxy.$success(result.msg)

  //更新购物车数量
  product.value.cart = result.data
}

//跳转购物车
const ToCart = () => proxy.$router.push('/cart/index')

//单独购买
const Buy = async (SkuData) => 
{
  //判断是否登录
  if(!proxy.$business.value.id)
  {
    proxy.$fail('请先登录')
    return false
  }

  //判断是否选择商品规格
  if(properties.value.length > 0 && !SkuData.selectedSkuComb)
  {
    proxy.$fail('请选择商品规格')
    return false
  }

  //购买数量
  var selectedNum = SkuData.selectedNum
  if(selectedNum <= 0)
  {
    proxy.$fail('购买数量不能小于等于0')
    return false
  }

  var relationids = []

  //有规格
  if(properties.value.length > 0)
  {
    var SkuProps = SkuData.selectedSkuComb.properties
    
    for(var item of SkuProps)
    {
      var id = item.v[0] ? item.v[0]['id'] : 0;
      if(id) relationids.push(id)
    }
  }
  //组装数据
  var params = {
    busid: proxy.$business.value.id,
    proid: proid,
    nums: selectedNum,
    relationids: relationids.join(','),//规格id
  }

  var result = await proxy.$POST({
    url: '/cart/buy',
    params
  })

  //隐藏弹出框
  SkuShow.value = false

  if(result.code == 0)
  {
    proxy.$fail(result.msg)
    return false
  }

  proxy.$router.push({path: '/cart/confirm',query:{cartids: result.data}})
}

//参与拼团
const JoinTeam = async () => 
{
  //没有参加具体的拼团活动
  if(!teamid)
  {
    proxy.$router.push({path: '/team/index',query:{proid: product.value.id}})
    return false
  }

  var SkuData = SkuRef.value.getSkuData()

  //判断是否登录
  if(!proxy.$business.value.id)
  {
    proxy.$fail('请先登录')
    return false
  }

  //判断是否选择商品规格
  if(properties.value.length > 0 && !SkuData.selectedSkuComb)
  {
    proxy.$fail('请选择商品规格')
    return false
  }

  var relationids = []

  //有规格
  if(properties.value.length > 0)
  {
    var SkuProps = SkuData.selectedSkuComb.properties
    
    for(var item of SkuProps)
    {
      var id = item.v[0] ? item.v[0]['id'] : 0;
      if(id) relationids.push(id)
    }
  }

  //规格ID 记录到cookie中
  // relationids: relationids.join(','),//规格id
  proxy.$cookies.set('relationids',relationids)

  //发起拼团
  if(teamid == 0)
  {
    //隐藏弹出框
    SkuShow.value = false
    
    proxy.$router.push({path: '/team/confirm',query:{proid: product.value.id}})
  }

  //隐藏弹出框
  SkuShow.value = false

  proxy.$router.push({path: '/team/confirm',query:{proid: product.value.id}})
}

</script>